<!--
 * @Descripttion:
 * @version:
 * @Date: 2021-04-20 11:06:21
 * @LastEditors: huzhushan@126.com
 * @LastEditTime: 2022-09-27 18:24:27
 * @Author: huzhushan@126.com
 * @HomePage: https://huzhushan.gitee.io/vue3-element-admin
 * @Github: https://github.com/huzhushan/vue3-element-admin
 * @Donate: https://huzhushan.gitee.io/vue3-element-admin/donate/
-->
<template>
  <div class="login">
    <!--    注册-->
    <el-dialog v-model="registerUser" title="注册账号" width="500px" center>
      <span>
        <el-form>
          <el-form-item>
            <el-input
              prefix-icon="User"
              style="width: 300px;"
              v-model="modelForm.username"
              placeholder="请输入账号"
              @blur="getUsernames"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              prefix-icon="PhoneFilled"
              style="width: 300px;"
              v-model="modelForm.phone"
              placeholder="请输入手机号"
              @blur="getPhones"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              prefix-icon="Lock"
              style="width: 170px;"
              v-model="modelForm.code"
              placeholder="请输入手机号验证码"
              @blur="getCodes"
            />
            &nbsp;&nbsp;
            <el-button
              type="primary"
              @click="getCode"
              :disabled="isShow === false"
            >
              <!--          60秒倒计时-->
              <span v-if="!isShow">{{ count }}秒后重试</span>
              <span v-else>获取验证码</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-input
              prefix-icon="Lock"
              style="width: 300px;"
              v-model="modelForm.password"
              placeholder="请输入密码"
            />
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="registerUser = false">取消</el-button>
          <el-button type="primary" @click="toregisterUser">
            注册账号
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!--    忘记密码-->
    <el-dialog v-model="forgetPassword" title="忘记密码" width="500px" center>
      <span>
        <el-form>
          <el-form-item>
            <el-input
              prefix-icon="User"
              style="width: 300px;"
              v-model="modelForm.username"
              placeholder="请输入要找回密码的账号"
              @blur="getUsername"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              prefix-icon="PhoneFilled"
              style="width: 300px;"
              v-model="modelForm.phone"
              placeholder="请输入账号绑定的手机号"
              @blur="getPhone"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              prefix-icon="Lock"
              style="width: 170px;"
              v-model="modelForm.code"
              placeholder="请输入手机号验证码"
              @blur="getCodes"
            />
            &nbsp;&nbsp;
            <el-button
              type="primary"
              @click="getCode"
              :disabled="isShow === false"
            >
              <!--          60秒倒计时-->
              <span v-if="!isShow">{{ count }}秒后重试</span>
              <span v-else>获取验证码</span>
            </el-button>
          </el-form-item>
          <el-form-item>
            <el-input
              prefix-icon="Lock"
              style="width: 300px;"
              v-model="modelForm.password"
              placeholder="请输入新密码"
              @blur="getPassword"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              prefix-icon="Lock"
              style="width: 300px;"
              v-model="modelForm.qrmm"
              placeholder="确认新密码"
              @blur="getqrmm"
            />
          </el-form-item>
        </el-form>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="forgetPassword = false">取消</el-button>
          <el-button type="primary" @click="toForgetPassword">
            忘记密码
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!--    手机号登录-->
    <el-dialog
      v-model="centerDialogVisible"
      title="手机号登录"
      width="500px"
      center
    >
      <span>
        <el-form>
          <el-form-item>
            <el-input
              prefix-icon="PhoneFilled"
              style="width: 300px;"
              v-model="modelForm.phone"
              placeholder="请输入手机号"
              @blur="getPhone"
            />
          </el-form-item>
          <!--        手机号验证码-->
          <el-form-item>
            <el-input
              prefix-icon="Lock"
              style="width: 200px;"
              v-model="modelForm.code"
              placeholder="请输入手机号验证码"
              @blur="getCodes"
            />
            &nbsp;&nbsp;
            <el-button
              type="primary"
              :disabled="isShow === false"
              @click="getCode"
            >
              <!--          60秒倒计时-->
              <span v-if="!isShow">{{ count }}秒后重试</span>
              <span v-else>获取验证码</span>
            </el-button>
          </el-form-item>
          <span class="code">请在60秒内输入验证码,否则将失效</span>
        </el-form>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="centerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="phoneLogin">
            登录
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-form class="form" :model="model" :rules="rules" ref="loginForm">
      <div class="login-bg">
        <img class="logo" src="@/assets/img/logo.jpg" alt="" />
        <span class="title">中国振涛银行 |</span>
        <span class="title1">个人网上银行</span>
        <h5 class="china">China Zhentao Bank</h5>
      </div>
      <br />
      <br />
      <br />
      <el-form-item prop="userName">
        <el-input
          class="text"
          v-model="model.userName"
          prefix-icon="User"
          clearable
          :placeholder="$t('login.username')"
        />
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          class="text"
          v-model="model.password"
          prefix-icon="Lock"
          show-password
          clearable
          :placeholder="$t('login.password')"
        />
      </el-form-item>
      <el-form-item prop="captcha">
        <div class="captcha">
          <el-input
            class="text"
            v-model="model.captcha"
            prefix-icon="Picture"
            placeholder="请输入验证码"
          ></el-input>
        </div>
        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
        <img :src="captchaSrc" @click="refreshCaptcha" style="width: 170px" />
      </el-form-item>
      <!--跳转手机号登录 -->
      <div class="phone">
        <a @click="centerDialogVisible = true">
          手机号登录
        </a>
        &nbsp;&nbsp;
        <a @click="forgetPassword = true">
          忘记密码
        </a>
        &nbsp;&nbsp;
        <a @click="registerUser = true">
          注册
        </a>
        &nbsp;&nbsp;&nbsp;&nbsp;
      </div>
      <el-form-item>
        <el-button
          :loading="loading"
          type="primary"
          class="btn"
          size="large"
          @click="submit"
        >
          {{ btnText }}
        </el-button>
      </el-form-item>
    </el-form>
  </div>

  <div class="change-lang">
    <change-lang />
  </div>
</template>

<script>
import {
  defineComponent,
  getCurrentInstance,
  reactive,
  toRefs,
  ref,
  computed,
  watch,
  onMounted,
} from 'vue'
import {
  GetValidateCode,
  Login,
  getPhone,
  getPhoneCode,
  getUsernameOne,
  updatePassword,
  getPhoneOne,
  register,
} from '@/api/login'
import { useRouter, useRoute } from 'vue-router'
import ChangeLang from '@/layout/components/Topbar/ChangeLang.vue'
import useLang from '@/i18n/useLang'
import { useApp } from '@/pinia/modules/app'
import { ElMessage } from 'element-plus'
export default defineComponent({
  components: { ChangeLang },
  name: 'login',
  setup() {
    const appStore = useApp()
    const { proxy: ctx } = getCurrentInstance() // 可以把ctx当成vue2中的this
    const router = useRouter()
    const route = useRoute()
    const { lang } = useLang()
    watch(lang, () => {
      state.rules = getRules()
    })
    const getRules = () => ({
      userName: [
        {
          required: true,
          message: ctx.$t('login.rules-username'),
          trigger: 'blur',
        },
      ],
      password: [
        {
          required: true,
          message: ctx.$t('login.rules-password'),
          trigger: 'blur',
        },
        {
          min: 6,
          max: 12,
          message: ctx.$t('login.rules-regpassword'),
          trigger: 'blur',
        },
      ],
      captcha: [
        {
          required: true,
          message: ctx.$t('login.rules-validate-code'),
          trigger: 'blur',
        },
      ],
    })
    // onMounted钩子函数
    onMounted(() => {
      state.refreshCaptcha()
    })
    const state = reactive({
      modelForm: {
        phone: '',
        code: '',
        username: '',
        password: '',
        qrmm: '',
      },
      centerDialogVisible: false,
      model: {
        userName: '',
        password: '',
        captcha: '', // 用户输入的验证码
        codeKey: '', // 后端返回的验证码key
      },
      //忘记密码弹框
      forgetPassword: false,
      //注册弹出框
      registerUser: false,
      getUsernames: () => {
        if (!state.modelForm.username.match(/^[0-9a-zA-Z]*$/)) {
          ElMessage.error({
            message: '用户名只能输入数字和字母',
            type: 'error',
          })
        } else {
          //唯一验证
          getUsernameOne(state.modelForm.username).then(res => {
            if (res.code !== 200) {
              ElMessage.success({
                message: '可以使用',
                type: 'success',
              })
            } else {
              ElMessage.error({
                message: '用户名已存在,请重新输入',
                type: 'error',
              })
            }
          })
        }
      },
      //忘记密码弹框
      getUsername: () => {
        if (state.modelForm.username == '') {
          ElMessage.error({
            message: '请输入用户名',
            type: 'error',
          })
        } else if (!state.modelForm.username.match(/^[0-9a-zA-Z]*$/)) {
          ElMessage.error({
            message: '用户名只能输入数字和字母',
            type: 'error',
          })
        } else {
          //唯一验证
          getUsernameOne(state.modelForm.username).then(res => {
            if (res.code !== 200) {
              ElMessage.error({
                message: '用户名不存在',
                type: 'error',
              })
              state.modelForm.username = ''
            }
          })
        }
      },
      //密码与确认密码认证
      getPassword: () => {
        if (state.modelForm.password == '') {
          ElMessage.error({
            message: '请输入密码',
            type: 'error',
          })
        } else if (
          state.modelForm.password.length < 6 ||
          state.modelForm.password.length > 12
        ) {
          ElMessage.error({
            message: '密码长度为6-12位',
            type: 'error',
          })
        }
      },
      getqrmm: () => {
        if (state.modelForm.qrmm == '') {
          ElMessage.error({
            message: '请输入确认密码',
            type: 'error',
          })
        } else if (state.modelForm.qrmm != state.modelForm.password) {
          ElMessage.error({
            message: '两次密码不一致',
            type: 'error',
          })
        }
      },
      //忘记密码
      toForgetPassword: () => {
        if (state.modelForm.username == '') {
          ElMessage.error({
            message: '请输入用户名',
            type: 'error',
          })
        } else if (!state.modelForm.username.match(/^[0-9a-zA-Z]*$/)) {
          ElMessage.error({
            message: '用户名只能输入数字和字母',
            type: 'error',
          })
        } else if (state.modelForm.phone == '') {
          ElMessage.error({
            message: '请输入手机号',
            type: 'error',
          })
        } else if (state.modelForm.phone.length != 11) {
          ElMessage.error({
            message: '请输入正确的手机号',
            type: 'error',
          })
        } else if (!state.modelForm.phone.match(/^[0-9]*$/)) {
          ElMessage.error({
            message: '请输入正确的手机号',
          })
        } else if (state.modelForm.code == '') {
          ElMessage.error({
            message: '请输入验证码',
            type: 'error',
          })
        } else if (state.modelForm.code.length < 6) {
          ElMessage.error({
            message: '验证码格式错误',
            type: 'error',
          })
        } else if (state.modelForm.password == '') {
          ElMessage.error({
            message: '请输入密码',
            type: 'error',
          })
        } else if (state.modelForm.qrmm == '') {
          ElMessage.error({
            message: '请输入确认密码',
            type: 'error',
          })
        } else if (state.modelForm.password != state.modelForm.qrmm) {
          ElMessage.error({
            message: '两次密码不一致',
            type: 'error',
          })
        } else {
          updatePassword(state.modelForm).then(res => {
            if (res.code == 200) {
              ElMessage.success({
                message: '密码修改成功',
                type: 'success',
              })
              state.forgetPassword = false
            } else {
              ElMessage.error({
                message: '密码修改失败',
                type: 'error',
              })
            }
          })
        }
      },
      //手机号离焦验证
      getPhone: () => {
        //验证手机号格式
        if (state.modelForm.phone == '') {
          ElMessage.error({
            message: '请输入手机号',
            type: 'error',
          })
        } else if (state.modelForm.phone.length != 11) {
          ElMessage.error({
            message: '请输入正确的手机号',
            type: 'error',
          })
        } else if (!state.modelForm.phone.match(/^[0-9]*$/)) {
          ElMessage.error({
            message: '请输入正确的手机号',
            type: 'error',
          })
        }
      },
      toregisterUser: () => {
        if (state.modelForm.username == '') {
          ElMessage.error({
            message: '请输入用户名',
            type: 'error',
          })
        } else if (
          state.modelForm.username.length < 5 ||
          state.modelForm.username.length > 8
        ) {
          ElMessage.error({
            message: '用户名长度为5-8位',
            type: 'error',
          })
        } else if (!state.modelForm.username.match(/^[0-9a-zA-Z]*$/)) {
          ElMessage.error({
            message: '用户名只能输入数字和字母',
            type: 'error',
          })
        } else if (state.modelForm.phone == '') {
          ElMessage.error({
            message: '请输入手机号',
            type: 'error',
          })
        } else if (state.modelForm.phone.length != 11) {
          ElMessage.error({
            message: '请输入正确的手机号',
            type: 'error',
          })
        } else if (!state.modelForm.phone.match(/^[0-9]*$/)) {
          ElMessage.error({
            message: '手机号只能是数字',
            type: 'error',
          })
        } else if (state.modelForm.password == '') {
          ElMessage.error({
            message: '请输入密码',
            type: 'error',
          })
        } else {
          register(state.modelForm).then(res => {
            if (res.code == 200) {
              ElMessage.success({
                message: '注册成功',
                type: 'success',
              })
              state.registerUser = false
            } else {
              ElMessage.error({
                message: '注册失败',
                type: 'error',
              })
            }
          })
        }
      },
      //注册唯一验证
      getPhones: () => {
        //验证手机号格式
        if (!state.modelForm.phone.match(/^[0-9]*$/)) {
          ElMessage.error({
            message: '请输入正确的手机号',
            type: 'error',
          })
        } else {
          getPhoneOne(state.modelForm.phone).then(res => {
            if (res.code == 200) {
              ElMessage.error({
                message: '手机号已存在，一个手机号只能注册一个账号',
                type: 'error',
              })
              state.modelForm.phone = ''
            }
          })
        }
      },
      getCodes: () => {
        //验证码验证只能是6位数和数字
        if (state.modelForm.code == '') {
          ElMessage.error({
            message: '请输入验证码',
            type: 'error',
          })
        } else if (state.modelForm.code.length != 6) {
          ElMessage.error({
            message: '验证码格式错误',
            type: 'error',
          })
        }
        //验证码只能是数字
        if (!state.modelForm.code.match(/^[0-9]*$/)) {
          ElMessage.error({
            message: '验证码为6位数字',
            type: 'error',
          })
        }
      },
      isShow: true,
      count: 60,
      // 获取验证码
      getCode: () => {
        if (state.modelForm.phone == '') {
          ElMessage.error({
            message: '请输入手机号',
            type: 'error',
          })
        } else if (state.modelForm.phone.length != 11) {
          ElMessage.error({
            message: '手机号格式错误',
            type: 'error',
          })
        } else {
          if (state.isShow) {
            state.isShow = false
            // 60秒倒计时
            setInterval(() => {
              state.count--
              if (state.count <= 0) {
                state.isShow = true
                state.count = 60
              }
            }, 1000)
          }
          getPhone(state.modelForm.phone).then(res => {
            if (res.code == 200) {
              ElMessage.success({
                message: '发送成功',
                type: 'success',
              })
            } else {
              ElMessage.error({
                message: '发送失败',
                type: 'error',
              })
            }
            console.log(res)
          })
        }
      },

      phoneLogin: async () => {
        if (state.modelForm.phone == '') {
          ElMessage.error({
            message: '请输入手机号',
            type: 'error',
          })
        } else if (state.modelForm.code == '') {
          ElMessage.error({
            message: '请输入验证码',
            type: 'error',
          })
        } else if (state.modelForm.code.length != 6) {
          ElMessage.error({
            message: '验证码格式错误',
            type: 'error',
          })
        }
        getPhoneOne(state.modelForm.phone).then(async res => {
          if (res.code !== 200) {
            ElMessage.error({
              message: '手机号未注册',
              type: 'error',
            })
            state.centerDialogVisible = false
            state.registerUser = true
          } else {
            const { code, data, message } = await getPhoneCode(state.modelForm)
            if (+code === 200) {
              ctx.$message.success({
                message: ctx.$t('login.loginsuccess'),
                duration: 1000,
              })
              const targetPath = decodeURIComponent(route.query.redirect)
              if (targetPath.startsWith('http')) {
                // 如果是一个url地址
                window.location.href = targetPath
              } else if (targetPath.startsWith('/')) {
                // 如果是内部路由地址
                router.push(targetPath)
              } else {
                router.push('/') // 请求成功以后，进入到首页
              }
              useApp().initToken(data)
            } else {
              ctx.$message.error(message)
            }
          }
        })
      },
      rules: getRules(),
      loading: false,
      captchaSrc: '',
      refreshCaptcha: async () => {
        const { data } = await GetValidateCode()
        console.log(data.codeKey)
        console.log(data.codeValue)
        //响应验证码ikey  保存到redis中的key
        state.model.codeKey = data.codeKey
        //图片验证码
        state.captchaSrc = data.codeValue
      },
      btnText: computed(() =>
        state.loading ? ctx.$t('login.logining') : ctx.$t('login.login')
      ),
      loginForm: ref(null),
      submit: () => {
        if (state.loading) {
          return
        }
        state.loginForm.validate(async valid => {
          if (valid) {
            state.loading = true
            const { code, data, message } = await Login(state.model)
            if (+code === 200) {
              ctx.$message.success({
                message: ctx.$t('login.loginsuccess'),
                duration: 1000,
              })
              const targetPath = decodeURIComponent(route.query.redirect)
              if (targetPath.startsWith('http')) {
                // 如果是一个url地址
                window.location.href = targetPath
              } else if (targetPath.startsWith('/')) {
                // 如果是内部路由地址
                router.push(targetPath)
              } else {
                router.push('/') // 请求成功以后，进入到首页
              }
              useApp().initToken(data)
            } else {
              ctx.$message.error(message)
            }
            state.loading = false
          }
        })
      },
    })
    return {
      ...toRefs(state),
    }
  },
})
</script>

<style lang="scss" scoped>
.code {
  color: red;
}
.title1 {
  color: #5c5c5c;
}
.china {
  color: black;
  font-size: 10px;
  margin-top: 5px;
  margin-left: 65px;
  font-family: 华文楷体;
}
.logo {
  width: 40px;
  margin: -50px -17px -18px 0px;
}
.login {
  position: relative;
  background: url('../../assets/img/login-bg.jpg');
  transition: transform 1s;
  transform: scale(1);
  width: 100%;
  height: 100%;
  overflow: hidden;
  .form {
    width: 520px;
    max-width: 100%;
    padding: 0 24px;
    box-sizing: border-box;
    margin: 160px auto 0;
    :deep {
      .el-input__wrapper {
        box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.1) inset;
        background: rgba(0, 0, 0, 0.1);
      }
      .el-input-group--append > .el-input__wrapper {
        border-top-right-radius: 0;
        border-bottom-right-radius: 0;
      }
      .el-input-group--prepend > .el-input__wrapper {
        border-top-left-radius: 0;
        border-bottom-left-radius: 0;
      }
    }
    .title {
      font-family: 华文楷体;
      color: black;
      text-align: center;
      font-size: 24px;
      margin: 0 0 20px 24px;
      line-height: 24px;
    }
    .text {
      font-size: 16px;
      :deep(.el-input__inner) {
        color: #fff;
        height: 48px;
        line-height: 48px;
        &::placeholder {
          color: rgba(255, 255, 255, 1);
        }
      }
    }
    .btn {
      width: 100%;
    }
  }
}
.change-lang {
  position: fixed;
  right: 20px;
  top: 20px;
  :deep {
    .change-lang {
      height: 24px;
      &:hover {
        background: none;
      }
      .icon {
        color: #fff;
      }
    }
  }
}
</style>
